import { BUNDLE_TYPE_ENUM } from "../base/EnumIndex";
import { Tools } from "../common/Tools";
import { AudioManager1 } from "../manager/AudioManager1";
import { ResManager1 } from "../manager/ResManager1";

const { ccclass } = cc._decorator;
/** 鼠标点击效果 */
@ccclass
export default class TouchEffect extends cc.Component {
    /** 是否吞噬事件 */
    private _isSwallow: boolean = false;

    onEnable() {
        if (this.node['_touchListener']) {
            this.node['_touchListener'].setSwallowTouches(this._isSwallow);
        }
    }

    touchPrefab: cc.Prefab;
    nodePool: cc.NodePool;
    onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.preventSwallow, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.preventSwallow, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.preventSwallow, this);
    }

    onDestroy() {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.preventSwallow, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.preventSwallow, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.preventSwallow, this);
        this.nodePool.clear();
    }

    async start() {
        this.nodePool = new cc.NodePool();
        this.touchPrefab = await ResManager1.ins.loadRes('prefab/node/clickPre', cc.Prefab);
    }

    preventSwallow(event: cc.Event.EventTouch) {
        // event.preventSwallow = true;
        // event.stopPropagation();
    }
    onTouchStart(event: cc.Event.EventTouch) {
        this.preventSwallow(event);

        // AudioManager.playAudio("clickAni", 0.25, BUNDLE_TYPE_ENUM.MAIN);
        let node = cc.find('Canvas/GameCommonLayer');
        if (node.childrenCount > 0) {
            AudioManager1.playClickAudio("clickAni", 0.25, BUNDLE_TYPE_ENUM.MAIN);
        }

        var isCliCkTexiaoBtnBendi = Tools.getStorage('isCliCkTexiaoBtn');
        // console.log('isCliCkTexiaoBtnBendi',isCliCkTexiaoBtnBendi);

        if (isCliCkTexiaoBtnBendi == "false") return;

        if (!this.touchPrefab) return;


        let touchNode = this.getTouchNode();
        touchNode.scale = 0.5;
        touchNode.getComponent(dragonBones.ArmatureDisplay).playAnimation('animation', 1);
        touchNode.setParent(this.node);

        let location = event.getLocation();
        let pos = Tools.getToNodePosForWorld(location, this.node);
        touchNode.setPosition(pos);

        cc.tween(touchNode).delay(0.6).call(() => {
            this.nodePool.put(touchNode)
        }).start();
    }

    getTouchNode() {
        if (this.nodePool.size() > 0) {
            return this.nodePool.get();
        } else {
            return cc.instantiate(this.touchPrefab);
        }
    }
}